package com.demo.web.security;


import com.demo.model.SysUser.SysUser;
import com.demo.service.User.SysUserservice;
import com.demo.tool.JWTUTIL;
import com.demo.tool.Token;
import com.demo.web.httpTool.httpResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
//认证成功会调用
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    //序列化以及反序列化
    private ObjectMapper objectMapper;

    //生成token
    @Autowired
    private JWTUTIL jwtutil;
    //redis工具 用于效验token
    @Autowired
    private Token tokenTool;
    @Autowired
    private SysUserservice sysUserservice;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取数据库认证通过后的用户
       SysUser sysUser= sysUserservice.getUserOneByName(authentication.getName());
       //用用户的id和name 生成token
        String token=jwtutil.getToken(sysUser.getUid(),sysUser.getUsername());
        //将token存入redis
        tokenTool.depositRedis(sysUser.getUsername(),token);
        Map map=new HashMap<>();
        map.put("token",token);

     httpResult httpResult= com.demo.web.httpTool.httpResult.builder().code(2000).message("登录成功").data(map).build();

     String jsontext=objectMapper.writeValueAsString(httpResult);

     response.setCharacterEncoding("utf-8");
     response.setContentType("application/json;charset=utf-8");

        PrintWriter printWriter=response.getWriter();

        printWriter.println(jsontext);
        printWriter.flush();
    }
}
